<template>
    <el-dialog v-model="visible" :title="title" :width="width" append-to-body destroy-on-close>
        <div class="preview-content">
            <FormRenderer v-show="!showData" ref="formRenderer" :requestHeaders="requestHeaders" :uploadApi="uploadApi"
                :disabled="disabled" />
            <MonacoEditor v-show="showData" v-model="formData" class="js-edit" language="json" />
        </div>
        <template #footer>
            <slot name="footer">
                <el-button v-if="!showData" @click="getFormData">获取数据</el-button>
                <el-button v-else @click="showData = false">返回</el-button>
                <el-button v-if="!showData" @click="disabled = !disabled">{{ disabled ? '编辑模式' : '预览模式' }}</el-button>
                <el-button @click="() => { visible = false; showData = false }">关闭</el-button>
            </slot>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, nextTick, inject } from 'vue'
import FormRenderer from './FormRenderer.vue'
import MonacoEditor from '@/components/designer/config-group/CodeEditor.vue'
import { formatCode } from '@/utils/formatCode'
import { ElMessage } from 'element-plus'

// 预览组件 需要从设计器获取请求信息
const formConfig = inject('formConfig')
const uploadApi = inject('uploadApi')
const requestHeaders = inject('requestHeaders')

const disabled = ref(false)

const formRenderer = ref()

const props = defineProps({
    title: {
        type: String,
        default: '表单预览'
    },
    width: {
        type: String,
        default: '70%'
    }
})

const visible = ref(false)
const showData = ref(false)
const formData = ref('')

const getFormData = async () => {
    await nextTick()
    try {
        const data = await formRenderer.value.getFormData()
        formData.value = await formatCode(JSON.stringify(data), 'json')
        showData.value = true
    } catch (err) {
        ElMessage.error(err.message ? err.message : '表单内容校验失败！')
    }
}

const open = async (jsonData) => {
    visible.value = true
    await nextTick()
    formRenderer.value.setFormJson(jsonData)
}

defineExpose({
    open
})
</script>
<style scoped>
.preview-content {
    max-height: 500px;
    overflow-y: auto;
}

.js-edit {
    height: 500px;
}
</style>